import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import 'amfe-flexible'; // 引入rem自适应

import api from "./libs/http/api.js";
import './libs/js/rem.js';

Vue.prototype.$api = api;
Vue.prototype.common = new Vue;
Vue.config.productionTip = false

// 导航守卫
// router.beforeEach((to, from, next) => {
//   next();
  // const appId = "wxf256d7e3627d81db";
  // let wxCode = getUrlParam("code");
  // let isGo = sessionStorage.getItem("go");
  // let openId = sessionStorage.getItem("id");
  // let fromurl = window.location.href;
  // var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=' + encodeURIComponent(fromurl) + '&response_type=code&scope=snsapi_userinfo&state=redirected#connect_redirect=1#wechat_redirect';
  // // 判断是否请求过
  // if (isGo != 1) {
  //   window.location.href = url;
  //   sessionStorage.setItem("go", 1);
  // } else {
  //   // 判断是否有wxCode没有openId
  //   if (wxCode && openId == null) {
  //     api.system
  //       .getOpenIdByWxCode(wxCode)
  //       .then(res => {
  //         console.log(res, "confirmFn");
  //         sessionStorage.setItem("id", res);
  //         next();
  //       })
  //       .catch(err => {});
  //   } else {
  //     next();
  //   }
  // }
// });

function getUrlParam(name) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

function init(func) {
  const appId = "wxf256d7e3627d81db"; // 线上
  // const appId = "wx005fe7ee9b7870eb"; // 测试
  let wxCode = getUrlParam("code");
  let isGo = sessionStorage.getItem("go");
  let openId = sessionStorage.getItem("id");
  let fromurl = window.location.href;
  // var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=' + encodeURIComponent(fromurl) + '&response_type=code&scope=snsapi_userinfo&state=redirected#connect_redirect=1#wechat_redirect';
  var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=' + encodeURIComponent(fromurl) + '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
  // 判断是否请求过
  if (isGo != 1) {
    sessionStorage.setItem("go", 1);
    window.location.href = url;
  } else {
    // 判断是否有wxCode没有openId
    if (wxCode && openId == null) {
      api.system
        .getOpenIdByWxCode(wxCode)
        .then(res => {
          sessionStorage.setItem("id", res);
          func();
        })
        .catch(err => {});
    } else {
      func();
    }
  }
}

Vue.prototype.init = init;

let vue = new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

export default vue
